package com.anycc.cloud.core.controller;

import com.anycc.cloud.common.dto.datatable.DataTableRequest;
import com.anycc.cloud.common.dto.datatable.DataTableResponse;
import com.anycc.cloud.common.dto.json.Response;
import com.anycc.cloud.common.dto.json.SuccessResponse;
import com.anycc.cloud.common.dto.query.OrderBy;
import com.anycc.cloud.core.dto.AccountDto;
import com.anycc.cloud.core.entity.Account;
import com.anycc.cloud.core.entity.Account;
import com.anycc.cloud.core.entity.Role;
import com.anycc.cloud.core.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * account controller
 */
@RestController
@RequestMapping("account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    /**
     * create new account
     *
     * @param account    account
     * @param confirmPwd confirm password
     * @return response
     */
    @PostMapping("create")
    public Response create(Account account, @RequestParam("confirmPwd") String confirmPwd) {
        this.accountService.create(account, confirmPwd);
        return new SuccessResponse();
    }

    /**
     * datatable paging query
     *
     * @param account    account
     * @param request DataTableRequest
     * @return DataTableResponse
     */
    @GetMapping("findByPaging")
    public DataTableResponse<Account> findByPaging(Account account, DataTableRequest request) {
        List<OrderBy> orders = new ArrayList<>();
        orders.add(new OrderBy("desc", "createTime"));
        return new DataTableResponse<Account>(accountService.findByPaging(account, request.buildPageRequest(orders)), request);
    }

    /**
     * find account by username
     *
     * @param username username
     * @return account
     */
    @GetMapping("findByUsername")
    public AccountDto findByUsername(@RequestParam("username") String username) {
        Account account = accountService.findByUsername(username);
        if (account != null) {
            return new AccountDto(account);
        }
        return null;
    }

    /**
     * update account
     */
    @PostMapping("update")
    public Response update(Account account) {
        accountService.update(account);
        return new SuccessResponse();
    }

    /**
     * delete account
     * @param id id
     * @return Response
     */
    @PostMapping("delete")
    public Response delete(@RequestParam("id") String id) {
        accountService.delete(id);
        return new SuccessResponse();
    }

    /**
     * find role by id
     *
     * @param id id
     * @return Account
     */
    @GetMapping("findById")
    public Account findById(@RequestParam("id") String id) {
        return accountService.findById(id);
    }

}
